const mongoose = require('mongoose')

const videoSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, '视频标题是必需的'],
    trim: true,
    minlength: [2, '标题至少需要2个字符'],
    maxlength: [100, '标题不能超过100个字符']
  },
  description: {
    type: String,
    required: [true, '视频描述是必需的'],
    trim: true,
    maxlength: [2000, '描述不能超过2000个字符']
  },
  fileName: {
    type: String,
    required: true
  },
  videoUrl: {
    type: String,
    required: true
  },
  thumbnail: {
    type: String,
    required: true
  },
  duration: {
    type: Number,
    required: true
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  category: {
    type: String,
    required: true,
    enum: ['娱乐', '音乐', '游戏', '科技', '教育', '生活', '体育', '新闻', '电影', '动漫', '搞笑', '旅游', '美食', '宠物', '时尚', '健康', '其他']
  },
  tags: [{
    type: String,
    trim: true
  }],
  privacy: {
    type: String,
    enum: ['public', 'unlisted', 'private'],
    default: 'public'
  },
  status: {
    type: String,
    enum: ['uploading', 'processing', 'ready', 'failed', 'pending'],
    default: 'uploading'
  },
  processingProgress: {
    type: Number,
    min: 0,
    max: 100,
    default: 0
  },
  errorMessage: {
    type: String,
    default: ''
  },
  formats: [{
    quality: String,
    url: String,
    size: Number
  }],
  views: {
    type: Number,
    default: 0
  },
  likes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  dislikes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  isRecommended: {
    type: Boolean,
    default: false
  },
  isFeatured: {
    type: Boolean,
    default: false
  },
  previewThumbnails: {
    type: String,
    default: null
  },
  previewVtt: {
    type: String,
    default: null
  }
}, {
  timestamps: true
})

// 索引
videoSchema.index({ title: 'text', description: 'text', tags: 'text' })

// 获取视频统计信息
videoSchema.methods.getStats = function() {
  return {
    views: this.views,
    likes: this.likes.length,
    dislikes: this.dislikes.length,
    comments: this.comments.length
  }
}

// 增加观看次数
videoSchema.methods.incrementViews = async function() {
  this.views += 1
  return this.save()
}

// 检查用户是否已点赞
videoSchema.methods.isLikedBy = function(userId) {
  return this.likes.includes(userId)
}

// 检查用户是否已点踩
videoSchema.methods.isDislikedBy = function(userId) {
  return this.dislikes.includes(userId)
}

// 处理点赞
videoSchema.methods.toggleLike = async function(userId) {
  const isLiked = this.likes.includes(userId)
  const isDisliked = this.dislikes.includes(userId)
  
  if (isLiked) {
    // 取消点赞
    this.likes = this.likes.filter(id => !id.equals(userId))
  } else {
    // 添加点赞
    this.likes.push(userId)
    // 如果已经点踩，则移除点踩
    if (isDisliked) {
      this.dislikes = this.dislikes.filter(id => !id.equals(userId))
    }
  }
  
  return this.save()
}

// 处理点踩
videoSchema.methods.toggleDislike = async function(userId) {
  const isDisliked = this.dislikes.includes(userId)
  const isLiked = this.likes.includes(userId)
  
  if (isDisliked) {
    // 取消点踩
    this.dislikes = this.dislikes.filter(id => !id.equals(userId))
  } else {
    // 添加点踩
    this.dislikes.push(userId)
    // 如果已经点赞，则移除点赞
    if (isLiked) {
      this.likes = this.likes.filter(id => !id.equals(userId))
    }
  }
  
  return this.save()
}

// 获取推荐视频
videoSchema.statics.getRecommended = async function(limit = 10) {
  return this.find({
    status: 'ready',
    privacy: 'public',
    isRecommended: true
  })
    .sort({ views: -1, createdAt: -1 })
    .limit(limit)
    .populate('user', 'username avatar')
}

// 获取热门视频
videoSchema.statics.getTrending = async function(limit = 10) {
  const oneWeekAgo = new Date()
  oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
  
  return this.find({
    status: 'ready',
    privacy: 'public',
    createdAt: { $gte: oneWeekAgo }
  })
    .sort({ views: -1 })
    .limit(limit)
    .populate('user', 'username avatar')
}

// 搜索视频
videoSchema.statics.search = async function(query, limit = 20) {
  return this.find(
    {
      $text: { $search: query },
      status: 'ready',
      privacy: 'public'
    },
    { score: { $meta: 'textScore' } }
  )
    .sort({ score: { $meta: 'textScore' } })
    .limit(limit)
    .populate('user', 'username avatar')
}

const Video = mongoose.model('Video', videoSchema)

module.exports = Video